package com.intellekt.ecert.login.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import com.intellekt.ecert.domain.CatalogoVO;
import com.intellekt.ecert.domain.JdbcDao;
import com.intellekt.ecert.domain.UsuarioVO;

public class LoginDaoImpl extends JdbcDao implements LoginDao {

	private String qryUsuarioPorUsername;
	private String qryPantallasPorRol;

	private static ParameterizedRowMapper<UsuarioVO> MAPPER_USR = new ParameterizedRowMapper<UsuarioVO>() {
		public UsuarioVO mapRow(ResultSet rs, int rowNum) throws SQLException {
			UsuarioVO obj = new UsuarioVO();

			obj.setUsername(rs.getString("USERNAME"));
			obj.setNombre(rs.getString("NOMBRE"));
			if(rs.getString("VIGENCIA").equals("A")){
				obj.setVigente(true);
			}else{
				obj.setVigente(false);
			}
			
			obj.setRolId(rs.getString("CVE_ROL"));
			obj.setRol(rs.getString("DES_ROL"));
			
			return obj;
		}

	};

	private static ParameterizedRowMapper<String> MAPPER_MENU = new ParameterizedRowMapper<String>() {
		public String mapRow(ResultSet rs, int rowNum) throws SQLException {
			return rs.getString("ID_PANTALLA");
		}

	};
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public UsuarioVO getUsuarioPorUsername(String username, String password) {
		if (log.isDebugEnabled()) {
			log.debug("getUsuarioDao...");
		}
		ArrayList params = new ArrayList();
		params.add(username);
		params.add(password);
		try {
			return (UsuarioVO) jdbcTemplate.queryForObject(qryUsuarioPorUsername, params.toArray(), MAPPER_USR);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public Map<String, String> getPantallasPorRol(String rolId) {
		if (log.isDebugEnabled()) {
			log.debug("getPantallasPorRol...");
		}
		List<String> listaPantallas =jdbcTemplate.query(qryPantallasPorRol, new Object[]{rolId}, MAPPER_MENU);
		return toMap(listaPantallas);
	}
	
	private Map<String, String> toMap(List<String> stringList) {
		Map<String, String> map = new HashMap<String, String>();
		for (String cadena: stringList) {
			map.put(cadena, null);
		}
		return map;
	}

	public void setQryUsuarioPorUsername(String qryUsuarioPorUsername) {
		this.qryUsuarioPorUsername = qryUsuarioPorUsername;
	}

	public void setQryPantallasPorRol(String qryPantallasPorRol) {
		this.qryPantallasPorRol = qryPantallasPorRol;
	}

}
